package com.cn.core.lambda;

import com.cn.core.utils.ClassUtils;
import com.cn.core.utils.SerializationUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author SHANGGUAN
 **/
public class SerializedLambdas {



    public static SerializedLambda resolve(SFunction<?, ?> lambda) {
        if (!lambda.getClass().isSynthetic()) {
            throw new IllegalArgumentException("Not a synthetic class: " + lambda.getClass());
        } else {
            try {
                ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(SerializationUtils.serialize(lambda))) {
                    protected Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException {
                        Class clazz;
                        try {
                            clazz = ClassUtils.toClassConfident(objectStreamClass.getName());
                        } catch (Exception var4) {
                            clazz = super.resolveClass(objectStreamClass);
                        }

                        return clazz == java.lang.invoke.SerializedLambda.class ? SerializedLambda.class : clazz;
                    }
                };
                Throwable var2 = null;

                SerializedLambda var3;
                try {
                    var3 = (SerializedLambda) objIn.readObject();
                } catch (Throwable var13) {
                    var2 = var13;
                    throw var13;
                } finally {
                    if (var2 != null) {
                        try {
                            objIn.close();
                        } catch (Throwable var12) {
                            var2.addSuppressed(var12);
                        }
                    } else {
                        objIn.close();
                    }

                }

                return var3;
            } catch (IOException | ClassNotFoundException var15) {
                throw new RuntimeException("This is impossible to happen");
            }
        }
    }


    @SafeVarargs
    public static <T, E> List<SerializedLambda> resolve(SFunction<T, E>... functions) {
        List<SerializedLambda> objects = new ArrayList<>();
        for (SFunction<T, E> function : functions) {
            SerializedLambda resolve = resolve(function);
            objects.add(resolve);
        }
        return objects;

    }
}
